package com.heima.admin.gateway.filter;

import com.heima.admin.gateway.utils.AppJwtUtil;
import io.jsonwebtoken.Claims;
import lombok.extern.log4j.Log4j2;
import org.apache.commons.lang3.StringUtils;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.annotation.Order;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

/**
 * 鉴权过滤器
 * @作者 itcast
 * @创建日期 2020/9/22 14:18
 **/
@Component
@Log4j2
@Order(0)
public class AuthorizeFilter implements GlobalFilter {
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        // 1. 判断请求路径是否是登录路径
        ServerHttpRequest request = exchange.getRequest(); // 请求对象
        ServerHttpResponse response = exchange.getResponse(); // 响应对象
        //1.1 是登录路径 放行
        if (request.getURI().getPath().contains("/login/in")) {
            return chain.filter(exchange);
        }
        // 2. 获取当前请求中的token信息
        try {
            String token = request.getHeaders().toSingleValueMap().get("token");
            // 3. token  不存在终止请求返回无权限
            if(StringUtils.isNotEmpty(token)){
                Claims claimsBody = AppJwtUtil.getClaimsBody(token);// 获取token 内容
                // 4. 获取token内容 判断token信息是否失效 是否合法
                int result = AppJwtUtil.verifyToken(claimsBody);
                if(result==-1||result==0){
                    // 5. 未失效 获取token中的用户ID 将id存入请求头中
                    Integer userId = (Integer) claimsBody.get("id");
                    log.info(" find userId: {}, from uri: {}",userId,request.getURI());
                    ServerHttpRequest newRequest = request.mutate().headers(header -> {
                        header.add("userId", String.valueOf(userId));
                    }).build();
                    exchange = exchange.mutate().request(newRequest).build();
                    return chain.filter(exchange);// 放行
                }else {
                    log.error("authorize is error: {}"," token is expired");
                }
            }else {
                log.error("authorize is error: {}"," token is not founded");
            }
        } catch (Exception e) {
            e.printStackTrace();
            log.error("authorize is error: {}",e.getMessage());
        }
        // 4.1 终止请求
        response.setStatusCode(HttpStatus.UNAUTHORIZED);
        return response.setComplete();
    }
}
